
import { defineStore } from "pinia";
import { computed, ref } from "vue";
import { useUserStore } from './user'
import { insertCartAPI, findNewCartListAPI, delCartAPI } from '@/apis/cart'

export const useCartStore = defineStore('cart', () => {
    const cartList = ref([])
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    const updateCartList = async () => {
        const res = await findNewCartListAPI();
        cartList.value = res.result
    }
    const addCart = async (goodsObj) => {
        console.log('token:', isLogin.value);
        if (isLogin.value) {
            const { skuId, count } = goodsObj;
            await insertCartAPI({ skuId, count })
            await updateCartList();
        } else {
            const item = cartList.value.find((item) => item.skuId === goodsObj.skuId)
            if (item) {
                item.count += goodsObj.count;
            } else {
                cartList.value.push(goodsObj)
            }
        }

    }
    const delCart = async (skuId) => {
        if (isLogin.value) {
            await delCartAPI([skuId])
            await updateCartList();
        } else {
            // 方法1 splice
            const idx = cartList.value.findIndex(item => item.skuId === skuId)
            cartList.value.splice(idx, 1)
            // 方法2 filter
            // cartList.value = cartList.value.filter(item => item.skuId !== skuId)
        }

    }
    // 单选功能
    const singleCheck = (skuId, selected) => {
        const item = cartList.value.find(item => item.skuId === skuId)
        item.selected = selected
    }
    // 全选功能
    const allCheck = (selected) => {
        cartList.value.forEach(item => item.selected = selected)
    }
    const clearCart = () => {
        cartList.value = []
    }
    const allCount = computed(() => cartList.value.reduce((sum, item) => sum + item.count, 0))
    const allPrice = computed(() => cartList.value.reduce((sum, item) => sum + item.count * item.price, 0))

    // 已选商品总数
    const selectedCount = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count, 0))
    // 已选商品总价
    const selectedPrice = computed(() => cartList.value.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0))

    const isAll = computed(() => cartList.value.every(item => item.selected))
    return {
        cartList,
        addCart,
        delCart,
        allCount,
        allPrice,
        singleCheck,
        isAll,
        allCheck,
        selectedCount,
        selectedPrice,
        clearCart,
        updateCartList
    }
}, {
    persist: true,
})